package com.newway.back.upload;

import com.newway.common.filepath.UploadFilePath;
import com.newway.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/system/file")
public class UploadFileController {

    @Autowired
    UploadFilePath uploadFilePath;

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file){
        if(file==null || file.isEmpty()){
            return Result.fail("文件不能为空");
        }
        try{
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            File uploadPath = new File(uploadFilePath.getUploadPath());
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            // 5. 生成唯一文件名
            String fileName = UUID.randomUUID() + fileExtension;
            // 6. 保存文件
            File dest = new File(uploadPath.getAbsolutePath() + File.separator + fileName);
            file.transferTo(dest);
            return Result.success(uploadFilePath.getMappingPath()+fileName);
        }catch (Exception e){
            return Result.fail("文件上传失败");
        }

    }

}
